package com.example.wechat.login.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.wechat.login.config.TencentSpeechConfig;
import com.example.wechat.login.dto.speech.SpeechRecognitionRequest;
import com.example.wechat.login.dto.speech.SpeechRecognitionResponse;
import com.example.wechat.login.dto.speech.SpeechTaskRequest;
import com.example.wechat.login.dto.speech.SpeechTaskResponse;
import com.example.wechat.login.mapper.SpeechRecognitionHistoryMapper;
import com.example.wechat.login.service.SpeechService;
import com.tencentcloudapi.asr.v20190614.AsrClient;
import com.tencentcloudapi.asr.v20190614.models.*;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * 语音服务实现类
 */
@Service
@Slf4j
public class SpeechServiceImpl implements SpeechService {

    private final AsrClient asrClient;

    @Value("${tencent.cloud.speech.callbackUrl}")
    public String callbackUrl;


    private  final SpeechRecognitionHistoryMapper historyRepository;

    public SpeechServiceImpl(AsrClient asrClient,SpeechRecognitionHistoryMapper historyRepository) {
        this.asrClient = asrClient;
        this.historyRepository = historyRepository;
    }

    @Override
    public SpeechRecognitionResponse recognizeSpeech(SpeechRecognitionRequest request) throws TencentCloudSDKException {

            // 创建SentenceRecognition请求
            SentenceRecognitionRequest req = new SentenceRecognitionRequest();
            req.setProjectId(0L); // 项目ID，默认为0
            req.setSubServiceType(2L); // 子服务类型，2表示语音识别
            req.setEngSerViceType(request.getEngineType()); // 识别引擎类型，这里使用中文普通话16k
            req.setSourceType(1L); // 音频来源，1表示音频数据
            req.setVoiceFormat(request.getAudioType()); // 音频格式
            req.setUsrAudioKey("audio_" + System.currentTimeMillis()); // 用户音频唯一标识
            req.setData(request.getAudioBase64()); // Base64编码的音频数据
            req.setDataLen((long) request.getAudioBase64().length()); // 音频数据长度

            // 调用SentenceRecognition接口
            SentenceRecognitionResponse resp = asrClient.SentenceRecognition(req);

            // 处理响应结果
            System.out.println("=== 短音频识别结果 ===");
            System.out.println("请求ID: " + resp.getRequestId());
            System.out.println("识别结果: " + resp.getResult());
            System.out.println("时长: " + resp.getAudioDuration());
        // 构建响应对象
        return SpeechRecognitionResponse.builder()
                .requestId(resp.getRequestId())
                .result(String.valueOf(resp.getResult()))
                .audioTime(Double.valueOf(resp.getAudioDuration()))
                .message("成功")
                .build();
    }

        /**
         * 将本地文件转换为Base64编码字符串
         * @param filePath 文件路径
         * @return Base64编码字符串
         * @throws IOException 文件读取异常
         */
        public static String fileToBase64(String filePath) throws IOException {
            File file = new File(filePath);
            byte[] fileBytes = new byte[(int) file.length()];

            try (FileInputStream fileInputStream = new FileInputStream(file)) {
                fileInputStream.read(fileBytes);
            }

            return Base64.getEncoder().encodeToString(fileBytes);
        }

    @Override
    public SpeechTaskResponse createSpeechTask(SpeechTaskRequest request) {
        try {


            // 实例化一个请求对象
            CreateRecTaskRequest req = new CreateRecTaskRequest();

            // 设置引擎模型类型
            req.setEngineModelType(request.getEngineType());

            // 设置语音声道数
            req.setChannelNum(request.getChannelNum().longValue());

            req.setResTextFormat(0L);
            // 设置回调URL
            if (StringUtils.hasText(request.getCallbackUrl())) {
                req.setCallbackUrl(request.getCallbackUrl());
            }

            // 设置语音数据来源
            if (StringUtils.hasText(request.getAudioUrl())) {
                req.setSourceType(0L);
                req.setUrl(request.getAudioUrl());
            } else {
                req.setSourceType(1L);
                String base64Audio = Base64.getEncoder().encodeToString(request.getFile().getBytes());
                req.setData(base64Audio);
            }

            // 设置音频格式

            // 设置是否过滤脏词
            req.setFilterDirty(request.getFilterDirty().longValue());

            // 设置是否过滤语气词
            req.setFilterModal(request.getFilterModal().longValue());

            // 设置是否进行阿拉伯数字智能转换
            req.setConvertNumMode(request.getConvertNumMode().longValue());

            // 设置是否开启说话人分离
            req.setSpeakerDiarization(request.getSpeakerDiarization().longValue());

            // 设置说话人分离人数
            req.setSpeakerNumber(request.getSpeakerNumber().longValue());

            req.setCallbackUrl(callbackUrl);

            // 发起请求并获取响应
            CreateRecTaskResponse resp = asrClient.CreateRecTask(req);

            // 构建响应对象
            return SpeechTaskResponse.builder()
                    .requestId(resp.getRequestId())
                    .taskId(String.valueOf(resp.getData().getTaskId()))
                    .status(0) // 任务等待中
                    .code(0)
                    .message("成功")
                    .build();

        } catch (TencentCloudSDKException e) {
            log.error("腾讯云语音识别任务创建异常", e);
            return SpeechTaskResponse.builder()
                    .code(Integer.parseInt(e.getErrorCode()))
                    .message(e.getMessage())
                    .build();
        } catch (Exception e) {
            log.error("语音识别任务创建异常", e);
            return SpeechTaskResponse.builder()
                    .code(-1)
                    .message(e.getMessage())
                    .build();
        }
    }

    @Override
    public SpeechTaskResponse querySpeechTask(String taskId) {
        try {
            // 实例化一个请求对象
            DescribeTaskStatusRequest req = new DescribeTaskStatusRequest();

            // 设置任务ID
            req.setTaskId(Long.valueOf(taskId));

            // 发起请求并获取响应
            DescribeTaskStatusResponse resp = asrClient.DescribeTaskStatus(req);

            // 获取任务状态
            TaskStatus taskStatus = resp.getData();

            // 构建响应对象
            return SpeechTaskResponse.builder()
                    .requestId(resp.getRequestId())
                    .taskId(taskId)
                    .status(taskStatus.getStatus().intValue())
                    .result(taskStatus.getResult())
                    .code(0)
                    .message("成功")
                    .build();

        } catch (TencentCloudSDKException e) {
            log.error("腾讯云语音识别任务查询异常", e);
            return SpeechTaskResponse.builder()
                    .taskId(taskId)
                    .code(Integer.parseInt(e.getErrorCode()))
                    .message(e.getMessage())
                    .build();
        } catch (Exception e) {
            log.error("语音识别任务查询异常", e);
            return SpeechTaskResponse.builder()
                    .taskId(taskId)
                    .code(-1)
                    .message(e.getMessage())
                    .build();
        }
    }
}
